#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 改造自 https://github.com/Sunbread/BullshitGenerator

import random
import json


class BullshitGenerator:
    def __init__(self, fileName, topic, num=100):
        self.fileName = fileName
        self.topic = topic
        self.num = num
        self.data = self.readJson()
        self.famous = self.data["famous"]  # a 代表前面垫话，b代表后面垫话
        self.before = self.data["before"]  # 在名人名言前面弄点废话
        self.after = self.data["after"]  # 在名人名言后面弄点废话
        self.bosh = self.data["bosh"]  # 代表文章主要废话来源
        self.nonstop = self.data["nonstop"]  # 要替换的结尾标点
        self.stop = self.data["stop"]  # 要保留的结尾标点
        self.complexity = 2
        self.bosh_next = self.Shuffle(self.bosh)
        self.famous_next = self.Shuffle(self.famous)

    def readJson(self):
        if self.fileName != '':
            strList = self.fileName.split(".")
            if strList[len(strList) - 1].lower() == "json":
                with open(self.fileName, mode='r', encoding="utf-8") as file:
                    return json.loads(file.read())

    def Shuffle(self, lists):
        pool = list(lists) * self.complexity
        while True:
            random.shuffle(pool)
            for element in pool:
                yield element

    def getSentence(self):
        xx = next(self.famous_next)
        xx = xx.replace("a", random.choice(self.before))
        xx = xx.replace("b", random.choice(self.after))
        return xx

    @staticmethod
    def nextParagraph(end):
        xx = end
        xx += "\r\n"
        xx += "　　"  # 两个全角空格
        return xx

    def forward(self):
        xx = self.topic.split(" ")
        for x in xx:
            # print(x + "：")
            tmp = ""  # 两个全角空格
            while len(tmp) < 50:
                branch = random.randint(0, self.num)
                if branch < 5:
                    if len(tmp) == 0 or tmp[-1] == "　":
                        pass
                    elif tmp[-1] in self.nonstop:
                        tmp = tmp[:-1]
                        tmp += self.nextParagraph("。")
                    elif tmp[-1] in self.stop:
                        tmp += self.nextParagraph("")
                    else:
                        tmp += self.nextParagraph("。")
                elif branch < 20:
                    tmp += self.getSentence()
                else:
                    tmp += next(self.bosh_next)
            tmp = tmp.replace("x", x)
            return tmp


if __name__ == "__main__":
    test = BullshitGenerator("data.json", "请假", 100)
    test.forward()
